import React, {useEffect, useRef, useState} from "react";
import {$toast} from "@kordar/easyui";
import {convertToText, resourceService} from "@kordar/easyui-tpl";
import {FormDataType} from "@kordar-lib/base";
import {tfield, tparam, tt} from "@kordar-lib/i18n";
import {Dialog, FileButton, Form, FormField, LinkButton, TextBox} from "rc-easyui";
import {SketchPicker} from "react-color";
import {datasetUpload} from "../../../../service/bucket_service";


const FormPanel = ({ctx, type, record, pageConfig, fetchConfig, close, refs, dataset}) => {

    const [color, setColor] = useState(record.color||"#fff");
    const [showPicker, setShowPicker] = useState(false)

    const [formData, loadFormData] = useState(record)
    const form = useRef(null)



    const rules = {
        name: {required: true},
        remark: {required: true},
    }

    const handleChange = (name, value) => {
        loadFormData({...formData, [name]: value})
    };

    useEffect(() => {
        ctx.setMethod("submitForm", onSubmit)
    }, [])

    // 提交数据
    const onSubmit = () => {

        form.current.validate((errors) => {
            if (errors != null) {
                $toast.error(convertToText(errors));
                return
            }

            let data = {
                id: parseInt(formData.id),
                name: formData.name,
                remark: formData.remark,
                dataset_id: parseInt(formData.dataset_id),
                color: color,
                thumb: formData.thumb,
                filename: formData.filename,
            }
            let formBody = {object: data, conditions: []}
            if (type === FormDataType.UPDATE) {
                formBody.conditions.push({key: "id", value: record.id})
            }
            resourceService.saveResult(ctx?.name(), type, formBody, () => {
                $toast.success(tt("save_success", "Message"))
                ctx.refresh()
                close()
            }).then(r => {});
        })

    }

    const x = () => {
      return (<div style={{background: color, width: 20, height: 20, borderRadius: 4, border: "1px solid black"}} onClick={() => setShowPicker(!showPicker)} />)
    }

    const onSelect = (files) => {
        const file = files[0];
        if (!files) {
            $toast.error("请上传有效文件")
            return;
        }

        const body = new FormData();
        body.append('file', file);
        body.append('bucket_id', dataset.bucket_id);
        body.append('dataset_id', dataset.id);
        body.append('type', "label");

        datasetUpload(body, {
            headers: {
                'Content-Type': 'multipart/form-data'
            }
        }).then(({data}) => {
            loadFormData({...formData, thumb: data.url, filename: data.filename});
        })
    }


    return (
        <>

            <Dialog
                title={" "}
                draggable
                closed={!showPicker}
                style={{zIndex: 999999}}
            >
                <SketchPicker color={formData.color} onChange={(c) => setColor(c.hex)}/>
            </Dialog>

            <Form ref={form}
                  model={formData}
                  labelWidth={120}
                  labelAlign="left"
                  errorType="tooltip"
                  rules={rules}
                  style={{minWidth: 500, padding: '20px'}}
                  onChange={handleChange}
            >


                <FormField name="name" label={tfield(pageConfig, 'label.name.label', 'Name') + ":"}>
                    <TextBox placeholder={tfield(pageConfig, 'label.name.placeholder', '')}
                             value={formData.name}></TextBox>
                </FormField>
                <FormField name="remark" label={tfield(pageConfig, 'label.remark.label', 'Remark') + ":"}>
                    <TextBox multiline placeholder={tfield(pageConfig, 'label.remark.placeholder', '')}
                             value={formData.remark}
                             style={{width: '100%', height: 120, padding: 5}}></TextBox>
                </FormField>
                <FormField name="color" label={tfield(pageConfig, 'label.color.label', 'Color') + ":"}>
                    {/*<TextBox placeholder={tfield(pageConfig, 'label.color.placeholder', '')} value={formData.color}></TextBox>*/}

                    <TextBox
                        value={color}
                        readonly
                        style={{paddingRight: 10}}
                        addonRight={x}
                    />

                </FormField>
                <FormField label={tfield(pageConfig, 'label.thumb.label', 'Thumb') + ":"}>
                    <FileButton
                        onSelect={onSelect}
                        style={{width: 100}}
                    >
                        {tfield(pageConfig, 'label.thumb.placeholder', 'Select a file')}
                    </FileButton>
                </FormField>

                <div className="admin-form-submit">
                    <LinkButton style={{width: 80}} onClick={onSubmit}
                                iconCls="icon-save">{tparam(pageConfig, 'submit.text', 'Submit')}</LinkButton>
                    <LinkButton style={{width: 80}} onClick={close}
                                iconCls="icon-cancel">{tparam(pageConfig, 'close.text', 'Close')}</LinkButton>
                </div>
            </Form>
        </>
    )
}

export default FormPanel;

